package com.mdnote.jianzhi_offer.string;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/10/11 0011
 * @description 剑指 Offer 05. 替换空格
 */
public class Offer05 {

    public static void main(String[] args) {
        Offer05 offer05 = new Offer05();
        String abcd_aefad_a = offer05.replaceSpace("we are happy");
        System.out.println(abcd_aefad_a);
    }

    public String replaceSpace(String s) {

        if (s == null || s.length() == 0) {
            return s;
        }

        // 可以先计算一下需要目标数组的大小
        char[] chars = s.toCharArray();
        int count = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ' ') {
                count++;
            }
        }

        if (count == 0) {
            return s;
        }

        char[] newChars = new char[s.length() + 2 * count];

        int i = chars.length - 1, j = newChars.length - 1;
        while (i >= 0 && j >=0) {
            if (chars[i] == ' ') {
                newChars[j--] = '0'; newChars[j--] = '2'; newChars[j--] = '%';
            } else {
                newChars[j] = chars[i];
                j--;
            }
            i--;
        }

        for (int k = 0; k < newChars.length; k++) {
            System.out.println(newChars[k]);
        }
        return new String(newChars, 0, newChars.length);
    }
}
